package com.ailanyin.modules.flowable.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ailanyin.common.base.exception.Assert;
import com.ailanyin.common.flowable.utils.ModelUtils;
import com.ailanyin.modules.flowable.domain.WfDeployForm;
import com.ailanyin.modules.flowable.domain.WfForm;
import com.ailanyin.modules.flowable.domain.vo.WfFormVo;
import com.ailanyin.modules.flowable.mapper.WfDeployFormMapper;
import com.ailanyin.modules.flowable.mapper.WfFormMapper;
import com.ailanyin.modules.flowable.service.IWfDeployFormService;
import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.FlowNode;
import org.flowable.bpmn.model.StartEvent;
import org.flowable.bpmn.model.UserTask;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author ailanyin
 * @version 1.0
 * @since 2022/12/13 0013 下午 16:52
 */
@Service
public class WfDeployFormServiceImpl implements IWfDeployFormService {

    @Resource
    private WfDeployFormMapper wfDeployFormMapper;
    @Resource
    private WfFormMapper wfFormMapper;

    @Override
    public boolean saveInternalDeployForm(String deployId, BpmnModel bpmnModel) {
        List<WfDeployForm> deployFormList = new ArrayList<>();
        // 获取开始节点
        StartEvent startEvent = ModelUtils.getStartEvent(bpmnModel);
        if (ObjectUtil.isNull(startEvent)) {
            Assert.fail("开始节点不存在，请检查流程设计是否有误！");
        }
        // 保存开始节点表单信息
        WfDeployForm startDeployForm = buildDeployForm(deployId, startEvent);
        if (ObjectUtil.isNotNull(startDeployForm)) {
            deployFormList.add(startDeployForm);
        }
        // 保存用户节点表单信息
        Collection<UserTask> userTasks = ModelUtils.getAllUserTaskEvent(bpmnModel);
        if (CollUtil.isNotEmpty(userTasks)) {
            for (UserTask userTask : userTasks) {
                WfDeployForm userTaskDeployForm = buildDeployForm(deployId, userTask);
                if (ObjectUtil.isNotNull(userTaskDeployForm)) {
                    deployFormList.add(userTaskDeployForm);
                }
            }
        }
        // 批量新增部署流程和表单关联信息
        return wfDeployFormMapper.insertBatch(deployFormList) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertWfDeployForm(WfDeployForm deployForm) {
        wfDeployFormMapper.deleteByDeployId(deployForm.getDeployId());
        return wfDeployFormMapper.insert(deployForm);
    }

    @Override
    public WfFormVo selectDeployFormByDeployId(String deployId) {
        return wfFormMapper.selectDeployFormByDeployId(deployId);
    }

    /**
     * 构建部署表单关联信息对象
     * @param deployId 部署ID
     * @param node 节点信息
     * @return 部署表单关联对象。若无表单信息（formKey），则返回null
     */
    private WfDeployForm buildDeployForm(String deployId, FlowNode node) {
        String formKey = null;
        if (node instanceof StartEvent) {
            formKey = ((StartEvent) node).getFormKey();
        } else if (node instanceof UserTask) {
            formKey = ((UserTask) node).getFormKey();
        }
        if (StrUtil.isEmpty(formKey)) {
            return null;
        }
        Long formId = Convert.toLong(StringUtils.substringAfter(formKey, "key_"));
        WfForm wfForm = wfFormMapper.selectByFormId(formId);
        if (ObjectUtil.isNull(wfForm)) {
            Assert.fail("表单信息查询错误");
        }
        WfDeployForm deployForm = new WfDeployForm();
        deployForm.setDeployId(deployId);
        deployForm.setNodeKey(node.getId());
        deployForm.setNodeName(node.getName());
        deployForm.setFormKey(formKey);
        deployForm.setContent(wfForm.getContent());
        return deployForm;
    }
}
